package com.shopp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopp.auto.JSONAuthentication;
import com.shopp.entity.ShUser;
import com.shopp.mapper.ShUserMapper;
import com.shopp.response.Result;
import com.shopp.utils.UpPhotoNameUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shopp
 * @since 2022-03-01
 */
@RestController
@RequestMapping("/sh-user")
public class ShUserController extends JSONAuthentication {
    @Autowired
    ShUserMapper shUserMapper;
    @ApiOperation(value = "添加用户")
    @PostMapping("/add")
    public void addUser(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("role") String role) throws Exception {
        ShUser  shUser = new ShUser();
        shUser.setUsername(username);
        shUser.setPassword(password);
        shUser.setRole(role);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        if (shUserMapper.selectOne(wrapper) != null) {
            Result error = Result.error().message("用户已存在");
            this.WriteJSON(request, response, error);
        } else {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
            Path path = Paths.get("D:\\自己的项目\\订餐系统\\order\\src\\assets\\picture\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url = fileName;
            shUser.setPicture(avatar_url);
            response.reset();

            shUser.setPassword(new BCryptPasswordEncoder().encode(shUser.getPassword()));
            if (shUserMapper.insert(shUser) > 0) {
                Result ok = Result.ok().message("注册成功");
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error().message("注册失败");
                this.WriteJSON(request, response, error);
            }
        }
    }
    @ApiOperation(value = "删除用户")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {
        int i = shUserMapper.deleteById(id);
        if (i > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改用户头像")
    @PostMapping("/updPic")
    public String updUserPic(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {
        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
            Path path = Paths.get("D:\\自己的项目\\订餐系统\\order\\src\\assets\\picture\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url = fileName;
            ShUser anUser = new ShUser();
            anUser.setId(id);
            anUser.setPicture(avatar_url);
            int n = shUserMapper.updateById(anUser);
            response.reset();
            if (n > 0) {
                Result result = Result.ok();
                this.WriteJSON(request, response, result);
            } else {
                Result result = Result.error();
                this.WriteJSON(request, response, result);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    @ApiOperation(value = "修改密码")
    @PostMapping("/updpassword")
    public void updpassword(HttpServletRequest request, HttpServletResponse response, @RequestParam("password") String password, @RequestParam("rpassword") String rpassword, @RequestParam("id") int id) throws Exception {
        ShUser anUser1 = shUserMapper.selectById(id);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password1 = new BCryptPasswordEncoder().encode(rpassword);
        if (encoder.matches(password, anUser1.getPassword())) {
            anUser1.setPassword(password1);

            int i = shUserMapper.updateById(anUser1);
            if (i > 0) {
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }

        } else {
            Result error = Result.error();
            error.setMessage("密码不正确");
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "通过用户id查找用户")
    @PostMapping("/findById")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {

        ShUser list = shUserMapper.selectById(id);
        if (list != null) {
            Result ok = Result.ok().data("user", list);
            this.WriteJSON(request, response, ok);
        }
        Result error = Result.error();
        error.setMessage("没有此用户");
        this.WriteJSON(request, response, error);
    }
    @ApiOperation(value = "通过名字查找用户")
    @PostMapping("/findByname")
    public void findByname(HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("username", username);
        Page<ShUser> page = new Page<>(size, current);
        Page<ShUser> pages = shUserMapper.selectPage(page, wrapper);
        List<ShUser> list = pages.getRecords();
        int total = shUserMapper.selectCount(wrapper);
        if (list.size() > 0) {
            Result ok = Result.ok().data("user", list).data("total", total);
            this.WriteJSON(request, response, ok);
        }
        Result error = Result.error();
        error.setMessage("没有此用户");
        this.WriteJSON(request, response, error);
    }

    @ApiOperation(value = "查找全部用户")
    @PostMapping("/find")
    public void findBynamea(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {

        Page<ShUser> page = new Page<>(current, size);
        Page<ShUser> pages = shUserMapper.selectPage(page, null);
        List<ShUser> list = pages.getRecords();
        int total = shUserMapper.selectCount(null);
        if (list.size() > 0) {
            Result ok = Result.ok().data("user", list).data("total", total);
            this.WriteJSON(request, response, ok);
        }
        Result error = Result.error();
        error.setMessage("没有用户");
        this.WriteJSON(request, response, error);
    }
    @ApiOperation(value = "通过用户id修改用户余额")
    @PostMapping("/updblanceByid")
    public void findByIda(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id, @RequestParam("balance") float balance) throws Exception {

        ShUser list = shUserMapper.selectById(id);
        float bal = list.getBalance();

        list.setBalance(bal + balance);
        if (shUserMapper.updateById(list) > 0) {
            Result ok = Result.ok().message("充值成功");
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "用户付款接口")
    @PostMapping("/updblanceByidfukuan")
    public void findByIdafukuan(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id, @RequestParam("price") float price) throws Exception {

        ShUser list = shUserMapper.selectById(id);
        float bal = list.getBalance();
        float yuer = bal - price;
        if (yuer > 0) {
            list.setBalance(yuer);
            if (shUserMapper.updateById(list) > 0) {
                Result ok = Result.ok().message("支付成功");
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error().message("支付失败");
                this.WriteJSON(request, response, error);
            }
        }
        Result error = Result.error().message("余额不足，支付失败");

        this.WriteJSON(request, response, error);
    }
}

